const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

/**
 * 生成测试用的收款明细数据
 */
async function seedTransactionData() {
  try {
    console.log('开始生成收款明细测试数据...');

    // 检查用户、渠道和产品是否存在
    const userCount = await prisma.user.count();
    if (userCount === 0) {
      console.error('错误: 用户数据不存在，请先运行 init-db.js');
      return;
    }

    const channelCount = await prisma.channel.count();
    if (channelCount === 0) {
      console.error('错误: 渠道数据不存在，请先运行 init-db.js');
      return;
    }

    const productCount = await prisma.product.count();
    if (productCount === 0) {
      console.error('错误: 产品数据不存在，请先运行 init-db.js');
      return;
    }

    // 获取用户、渠道和产品数据
    const users = await prisma.user.findMany();
    const channels = await prisma.channel.findMany();
    const products = await prisma.product.findMany();

    // 创建班次数据
    const shiftTypes = ['morning', 'middle', 'evening'];
    const shifts = [];

    // 首先清理可能存在的旧数据
    console.log('清理现有数据...');
    // 删除支付记录
    await prisma.payment.deleteMany({});
    // 删除订单项
    await prisma.orderItem.deleteMany({});
    // 删除订单
    await prisma.order.deleteMany({});
    // 删除班次渠道销售记录
    await prisma.shiftChannelSale.deleteMany({});
    // 删除班次支付方式记录
    await prisma.shiftPayment.deleteMany({});
    // 删除班次
    await prisma.shift.deleteMany({});
    console.log('数据清理完成');

    // 为过去30天创建班次数据
    for (let i = 0; i < 30; i++) {
      const date = new Date();
      date.setDate(date.getDate() - i);
      
      // 每天创建三个班次
      for (const shiftType of shiftTypes) {
        const user = users[Math.floor(Math.random() * users.length)];
        
        let startHour, endHour;
        if (shiftType === 'morning') {
          startHour = 8;
          endHour = 14;
        } else if (shiftType === 'middle') {
          startHour = 14;
          endHour = 20;
        } else {
          startHour = 20;
          endHour = 23;
        }
        
        const startTime = new Date(date);
        startTime.setHours(startHour, 0, 0, 0);
        
        const endTime = new Date(date);
        endTime.setHours(endHour, 0, 0, 0);
        
        // 创建班次记录
        const shift = await prisma.shift.create({
          data: {
            cashierId: user.id,
            startTime,
            endTime,
            status: 'ended',
            orderCount: 0, // 将在创建订单后更新
            totalSales: 0,  // 将在创建订单后更新
            updatedAt: new Date() // 添加 updatedAt 字段
          }
        });
        
        shifts.push(shift);
      }
    }
    
    console.log(`已创建 ${shifts.length} 条班次数据`);

    // 生成唯一订单号的计数器
    let orderCounter = 1;

    // 为每个班次创建订单和支付数据
    const orderStatuses = ['completed', 'paid', 'refunded'];
    const paymentMethods = ['cash', 'wechat', 'alipay', 'card'];
    
    let totalOrders = 0;
    
    for (const shift of shifts) {
      // 每个班次随机创建5-15个订单
      const orderCount = Math.floor(Math.random() * 11) + 5;
      let shiftTotalSales = 0;
      
      for (let i = 0; i < orderCount; i++) {
        const orderDate = new Date(shift.startTime);
        // 随机设置订单时间在班次时间范围内
        const randomMinutes = Math.floor(Math.random() * ((shift.endTime - shift.startTime) / 60000));
        orderDate.setMinutes(orderDate.getMinutes() + randomMinutes);
        
        // 随机选择渠道
        const channel = channels[Math.floor(Math.random() * channels.length)];
        
        // 随机选择状态
        const status = orderStatuses[Math.floor(Math.random() * orderStatuses.length)];
        
        // 创建全局唯一的订单号
        const timestamp = new Date().getTime();
        const orderNo = `ORD${timestamp}${String(orderCounter++).padStart(5, '0')}`;
        
        // 创建2-5个订单项
        const itemCount = Math.floor(Math.random() * 4) + 2;
        const orderItems = [];
        let orderTotal = 0;
        
        for (let j = 0; j < itemCount; j++) {
          // 随机选择产品
          const product = products[Math.floor(Math.random() * products.length)];
          
          // 随机数量1-5
          const quantity = Math.floor(Math.random() * 5) + 1;
          
          // 计算价格
          const price = product.price;
          const itemTotal = price * quantity;
          orderTotal += itemTotal;
          
          orderItems.push({
            productId: product.id,
            quantity,
            price
          });
        }
        
        // 创建订单记录
        const order = await prisma.order.create({
          data: {
            orderNo,
            userId: shift.cashierId,
            channelId: channel.id,
            total: orderTotal,
            status,
            createdAt: orderDate,
            updatedAt: orderDate,
            shiftId: shift.id,
            items: {
              create: orderItems.map(item => ({
                ...item,
                updatedAt: orderDate // 添加 updatedAt 字段
              }))
            }
          }
        });
        
        // 如果订单状态为退款，修改总金额为负数
        if (status === 'refunded') {
          orderTotal = -orderTotal;
          
          // 更新订单的总金额
          await prisma.order.update({
            where: { id: order.id },
            data: { total: orderTotal }
          });
        }
        
        // 更新班次的订单总数和销售额
        shiftTotalSales += orderTotal;
        
        // 创建支付记录
        const paymentMethod = paymentMethods[Math.floor(Math.random() * paymentMethods.length)];
        
        await prisma.payment.create({
          data: {
            orderId: order.id,
            method: paymentMethod,
            amount: Math.abs(orderTotal), // 支付金额始终为正
            status: status === 'refunded' ? 'refunded' : 'completed',
            createdAt: orderDate,
            updatedAt: orderDate
          }
        });
        
        totalOrders++;
      }
      
      // 更新班次的统计数据
      await prisma.shift.update({
        where: { id: shift.id },
        data: {
          orderCount: orderCount,
          totalSales: shiftTotalSales,
          averageOrder: shiftTotalSales / orderCount
        }
      });
      
      // 创建班次支付方式明细
      for (const method of paymentMethods) {
        // 随机分配金额
        const amount = Math.random() * shiftTotalSales * 0.5;
        
        if (amount > 0) {
          await prisma.shiftPayment.create({
            data: {
              shiftId: shift.id,
              paymentMethod: method,
              amount: amount,
              systemAmount: amount,
              actualAmount: amount,
              createdAt: new Date() // 这里不需要添加 updatedAt，因为 ShiftPayment 模型可能没有这个字段
            }
          });
        }
      }
      
      // 创建班次渠道销售明细
      for (const channel of channels) {
        // 随机分配金额
        const amount = Math.random() * shiftTotalSales * 0.3;
        
        if (amount > 0) {
          await prisma.shiftChannelSale.create({
            data: {
              shiftId: shift.id,
              channelId: channel.id,
              amount: amount,
              createdAt: new Date() // 这里不需要添加 updatedAt，因为 ShiftChannelSale 模型可能没有这个字段
            }
          });
        }
      }
    }
    
    console.log(`已创建 ${totalOrders} 条订单数据`);
    console.log('收款明细测试数据生成完成');

  } catch (error) {
    console.error('生成收款明细测试数据失败:', error);
  } finally {
    await prisma.$disconnect();
  }
}

// 执行数据生成
seedTransactionData()
  .catch(e => {
    console.error('执行脚本时出错:', e);
    process.exit(1);
  }); 